package com.cqh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqh.common.BaseContext;
import com.cqh.common.CustomException;
import com.cqh.entity.AddressBook;
import com.cqh.entity.Orders;
import com.cqh.entity.ShoppingCart;
import com.cqh.entity.User;
import com.cqh.mapper.OrdersMapper;
import com.cqh.service.AddressBookService;
import com.cqh.service.OrdersService;
import com.cqh.service.ShoppingCartService;
import com.cqh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrdersServiceIMpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired

    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    /**
     * 下单
     * @param orders
     */
    @Override
    @Transactional
    public void submint(Orders orders) {
        Long userId= BaseContext.getCurrent();
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper=new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list=shoppingCartService.list(shoppingCartLambdaQueryWrapper);
          if (list==null||list.size()==0){
              throw  new CustomException("购物车为空，不能下单");
          }
        User user=userService.getById(userId);
         AddressBook addressBook= addressBookService.getById(orders.getAddressBookId()) ;
         if (addressBook==null){
             throw  new CustomException("用户地址信息有误，不能下单");
         }
        Long id=IdWorker.getId();
        orders.setNumber(String.valueOf(id));
         this.save(orders);

    }
}
